package com.fruits.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        //1.获取参数
        String methodStr = req.getParameter("method");
        //如果methodStr为null，同意跳转到首页
        if(methodStr==null||methodStr.equals("")){
            methodStr="index";
        }
        //2.通过反射的方法获取调用方法
        Class clazz= this.getClass();
        //获取方法
        try {
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
           Object result = method.invoke(this, req, resp);
            if(result!=null){
                String resultStr=(String) result;
                //对结果进行处理
                if(((String) result).indexOf("forward:")!=1){
                   String path =resultStr.substring(resultStr.indexOf(":")+1);
                    req.getRequestDispatcher(path).forward(req,resp);
                } else if (resultStr.indexOf(":")!=-1) {
                    String path =resultStr.substring(resultStr.indexOf(":")+1);
                    resp.sendRedirect(req.getContextPath()+path);
                    
                }else {//直接响应字符串
                    resp.getWriter().println(resultStr);
                }
            }



        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
    public String index(HttpServletRequest req, HttpServletResponse resp){
        return "forward:/index.jsp";
    }
}
